package com.quectel.core.module.partybuildingmeeting.impl;


import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.func.LambdaUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.base.Preconditions;
import com.quectel.constant.core.partybuilding.PartyBuildingMeetingConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.partybuilding.dto.PartyOrganizationDto;
import com.quectel.core.module.partybuilding.dto.PartyPersonDto;
import com.quectel.core.module.partybuilding.service.PartyOrganizationService;
import com.quectel.core.module.partybuildingmeeting.dao.PartyBuildingMeetingDao;
import com.quectel.core.module.partybuildingmeeting.dao.PartyBuildingMeetingPersonBindingDao;
import com.quectel.core.module.partybuildingmeeting.dto.PartyBuildingMeetingDto;
import com.quectel.core.module.partybuildingmeeting.dto.PartyBuildingMeetingPersonBindingDto;
import com.quectel.core.module.partybuildingmeeting.entity.PartyBuildingMeetingEntity;
import com.quectel.core.module.partybuildingmeeting.entity.PartyBuildingMeetingPersonBindingEntity;
import com.quectel.core.module.partybuildingmeeting.service.PartyBuildingMeetingExperienceRecordService;
import com.quectel.core.module.partybuildingmeeting.service.PartyBuildingMeetingPersonBindingService;
import com.quectel.core.module.partybuildingmeeting.service.PartyBuildingMeetingService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
/**
 *
 * @author bob
 * @email bob.yu@quectel.com
 * @date 2023/05/24 11:38
 */
@DubboService
public class PartyBuildingMeetingServiceImpl implements PartyBuildingMeetingService {

    private static final Logger LOGGER = LoggerFactory.getLogger(PartyBuildingMeetingServiceImpl.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> PARTY_BUILDING_MEETING_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "PARTY_BUILDING_MEETING_CACHE_BY_ID:%d", id);

    /**
     * 清除缓存方法
     */
    private static final Consumer<PartyBuildingMeetingDto> CLEAR_CACHE_FUNC = dto -> {
        CacheKit.invalidRedisCache(PARTY_BUILDING_MEETING_CACHE_BY_ID_FUNC.apply(dto.getId()));
    };

    @Autowired
    private PartyBuildingMeetingDao partyBuildingMeetingDao;
    @Autowired
    private PartyOrganizationService partyOrganizationService;
    @Autowired
    private PartyBuildingMeetingPersonBindingDao meetingPersonBindingDao;
    @Autowired
    private PartyBuildingMeetingPersonBindingService meetingPersonBindingService;
    @Autowired
    private PartyBuildingMeetingExperienceRecordService partyBuildingMeetingExperienceRecordService;


    @Override
    public Long saveOrUpdate(PartyBuildingMeetingDto partyBuildingMeetingDto) {

        // 报名提醒时间
        if(!PartyBuildingMeetingConstants.RemindType.NO_NEED.getType().equals(partyBuildingMeetingDto.getRemindType())){
            PartyBuildingMeetingConstants.RemindType byType = PartyBuildingMeetingConstants.RemindType.getByType(partyBuildingMeetingDto.getRemindType());
            Preconditions.checkNotNull(byType);
            DateTime dateTime = DateUtil.offsetMinute(partyBuildingMeetingDto.getStartTime(), -byType.getOffsetTime());
            partyBuildingMeetingDto.setRemindTime(dateTime);
        }


        if (partyBuildingMeetingDto.getId() == null) {
            Long id = save(partyBuildingMeetingDto);
            partyBuildingMeetingDto.setId(id);
        } else {
            updateById(partyBuildingMeetingDto);
        }

        // 删除绑定关系
        meetingPersonBindingDao.delete(new LambdaQueryWrapper<PartyBuildingMeetingPersonBindingEntity>()
                .eq(PartyBuildingMeetingPersonBindingEntity::getPartyBuildingMeetingId, partyBuildingMeetingDto.getId()));

        // 绑定下党员信息到中间表
        for (PartyPersonDto personDto : partyBuildingMeetingDto.getPartyPersonList()) {
            PartyBuildingMeetingPersonBindingDto meetingPersonBindingDto = new PartyBuildingMeetingPersonBindingDto();
            meetingPersonBindingDto.setId(Snowflake.nextId());
            meetingPersonBindingDto.setPartyBuildingMeetingId(partyBuildingMeetingDto.getId());
            meetingPersonBindingDto.setPartyPersonId(personDto.getId());
            meetingPersonBindingService.save(meetingPersonBindingDto);
        }
        return partyBuildingMeetingDto.getId();
    }

    @Override
    public PartyBuildingMeetingDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                PARTY_BUILDING_MEETING_CACHE_BY_ID_FUNC.apply(id),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public PartyBuildingMeetingDto selectById(Long id){
            PartyBuildingMeetingEntity entity = partyBuildingMeetingDao.selectById(id);
        return paddingField(CopyUtils.copyObj(entity,PartyBuildingMeetingDto.class));
    }

    @Override
    public List<PartyBuildingMeetingDto> queryList(Map<String,Object> params){
        List<PartyBuildingMeetingEntity> list = partyBuildingMeetingDao.queryList(params);
        List<PartyBuildingMeetingDto> result =  CopyUtils.copyList(list,PartyBuildingMeetingDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    /**
     * 查询列表 不对内部对象进行填充速度较快
     *
     * @param params
     * @return
     */
    @Override
    public List<PartyBuildingMeetingDto> queryListWithoutPadding(Map<String, Object> params) {
        List<PartyBuildingMeetingEntity> list = partyBuildingMeetingDao.queryList(params);
        return CopyUtils.copyList(list,PartyBuildingMeetingDto.class);
    }

    /**
     * 此方法慎用 禁止填充List一类 比如一个人有多个地址这里不允许填充
     * 填充的原则是: 1:被填充对象不经常变换 2:根据id可以走缓存 3数据足够简单 比如设备类型 所属园区等
     *
     * @param dto
     * @return
     */
    private PartyBuildingMeetingDto paddingField(PartyBuildingMeetingDto dto){
        if (dto != null){
            if (dto.getPartyId()!=null){
                PartyOrganizationDto organizationDto = partyOrganizationService.selectCacheById(dto.getPartyId());
                if (organizationDto!=null){
                    dto.setPartyName(organizationDto.getName());
                }
            }

            Map<String, Object> sqlMap = new HashMap<>();
            sqlMap.put(LambdaUtil.getFieldName(PartyBuildingMeetingPersonBindingDto::getPartyBuildingMeetingId), dto.getId());
            int totalPersonCount = meetingPersonBindingService.queryTotal(sqlMap);
            dto.setTotalPersonCount(totalPersonCount);

            int meetingExperienceCount = partyBuildingMeetingExperienceRecordService.queryTotal(sqlMap);
            dto.setMeetingExperienceCount(meetingExperienceCount);

            sqlMap.put(LambdaUtil.getFieldName(PartyBuildingMeetingPersonBindingDto::getSignStatus), PartyBuildingMeetingConstants.SignStatus.SIGN.getStatus());
            int totalJoinCount = meetingPersonBindingService.queryTotal(sqlMap);
            dto.setTotalJoinCount(totalJoinCount);
        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params){
        return partyBuildingMeetingDao.queryTotal(params);
    }

    @Override
    public Long save(PartyBuildingMeetingDto dto){
        PartyBuildingMeetingEntity entity = CopyUtils.copyObj(dto,PartyBuildingMeetingEntity.class);
        entity.setId(Snowflake.nextId());
        partyBuildingMeetingDao.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateById(PartyBuildingMeetingDto dto){
        PartyBuildingMeetingEntity entity = CopyUtils.copyObj(dto,PartyBuildingMeetingEntity.class);

        partyBuildingMeetingDao.updateById(entity);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void updateAllColumnById(PartyBuildingMeetingDto dto) {
       PartyBuildingMeetingEntity entity = CopyUtils.copyObj(dto,PartyBuildingMeetingEntity.class);

       MyBatisPlusUtils.updateAllColumnById(entity, partyBuildingMeetingDao);

       CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void deleteById(Long id){

        CLEAR_CACHE_FUNC.accept(selectById(id));

        partyBuildingMeetingDao.deleteById(id);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids){
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
